﻿//----------------------------------------------------
//    版权：
//    作者：
//建立时间：2012-09-11 00:00:33
//    描述：
//----------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;

using System.Data.Entity.Core.EntityClient;
using System.Linq;
using System.Text;
using WinnerCMS.Common;
using WinnerCMS.Model;

namespace WinnerCMS.Data
{
    /// <summary>
    /// 数据访问层CMS_Tag。
    /// </summary>
    public class TagsDal
    {
        #region  添加数据
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="tags"></param>
        /// <param name="modelId"></param>
        /// <param name="contentId"></param>
        /// <param name="userId"></param>
        public void Add(string tags, byte modelId, int contentId, int userId)
        {
            string[] arrTag = tags.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            //using (Entities db = new Entities())
            //{
            //    var notin =
            //        arrTag.Except(
            //            db.Tags.Where(x => arrTag.Contains(x.TagName))
            //              .Select(x => x.TagName)
            //              .ToList())
            //              .Select(x => new Tag() { TagName = x, ModelId = modelId, UserId = userId });

            //    foreach (var v in notin)
            //    {
            //        db.Tags.Add(v);
            //    }
            //    db.SaveChangesAsync().Wait();
            //}
            //using (Entities db = new Entities())
            //{
            //    var tagList = db.Tags.Where(x => arrTag.Contains(x.TagName) && x.ModelId == modelId);
            //    tagList.ForEach(x =>
            //    {
            //        x.Cores.Clear();
            //        x.Cores.Add(db.Cores.Find(contentId));
            //    });
            //    db.SaveChangesAsync().Wait();
            //}
             
            using (Entities db = new Entities())
            {
                var notin =
                    arrTag.Except(
                        db.Tags.Where(x => arrTag.Contains(x.TagName))
                          .Select(x => x.TagName)
                          .ToList())
                          .Select(x => new Tag() { TagName = x, ModelId = modelId, UserId = userId });

                foreach (var v in notin)
                {
                    db.Tags.Add(v);
                }
                db.SaveChanges();
            
                db.Database.ExecuteSqlCommand("DELETE FROM CMS_CoreTags WHERE Core_Id={0}", contentId);

                db.Database.ExecuteSqlCommand("INSERT INTO CMS_CoreTags (Core_Id,Tag_Id) SELECT " + contentId + ",Id FROM CMS_Tags WHERE TagName IN ('" + string.Join("','", arrTag) + "') AND ModelID=" + modelId);
            }
        }
        #endregion

        #region 取得内容的标签
        /// <summary>
        /// 取得内容的标签
        /// </summary>
        /// <param name="contentId"></param>
        /// <returns></returns>
        public IList<Tag> ContentTags(int contentId)
        {
            using (Entities db = new Entities())
            {
                return db.Tags.Where(x => x.Cores.Any(y => y.Id == contentId)).ToList();
            }
        }
        #endregion

        #region 绑定指定tag内容

        /// <summary>
        /// 绑定指定tag内容
        /// </summary>
        /// <param name="tagId"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> BindList(int tagId, PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                try
                {
                    var query = db.Cores.Where(x => x.TagsInfos.Any(y => y.Id == tagId)).Select(x => new
                    {
                        x.Id,
                        x.CategoryId,
                        x.ContentTitle,
                        x.TemplateFileName,
                        x.UpdateTime
                    });

                    pp.RecordCount = query.Count();

                    var list = query.OrderByDescending(x => x.Id).Skip(pp.Skip).Take(pp.PageSize).ToArray();

                    return list.Select(x => new Core()
                    {
                        Id = x.Id,
                        ContentTitle = x.ContentTitle,
                        CategoryId = x.CategoryId,
                        TemplateFileName = x.TemplateFileName,
                        UpdateTime = x.UpdateTime
                    }).ToList();
                }
                catch
                {
#if DEBUG
                    throw;
#else 
                    return new List<Core>();
#endif

                }
            }
        }
        /// <summary>
        /// 后台管理绑定
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="tagName"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Tag> BindList(byte modelId, string tagName, PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from x in db.Tags where x.ModelId == modelId select x;
                if (string.IsNullOrEmpty(tagName) == false)
                {
                    query = query.Where(x => x.TagName.Contains(tagName));
                }
                pp.RecordCount = query.Count();

                return query.OrderByDescending(x => x.Id).Skip(pp.Skip).Take(pp.PageSize).ToList();
            }
        }
        #endregion

        #region 内容下所有模型

        /// <summary>
        /// 内容下所有模型
        /// </summary>
        /// <param name="contentId"></param>
        /// <returns></returns>
        public Tag[] AllTags(int contentId)
        {
            using (Entities db = new Entities())
            {
                var query = db.Tags.Where(x => x.Cores.Any(y => y.Id == contentId));

                return query.ToArray();
            }
        }
        #endregion
    }
}